package com.yh.csx.crm.webapi.controller;


import com.alibaba.fastjson.JSON;
import com.yh.csx.crm.appapi.controller.BaseController;
import com.yh.csx.crm.core.entity.CommonResponse;
import com.yh.csx.crm.core.enums.ApprovalTypeEnum;
import com.yh.csx.crm.core.enums.CooperationModeEnum;
import com.yh.csx.crm.core.enums.CustomerStatusEnum;
import com.yh.csx.crm.core.enums.UploadFileTypeEnum;
import com.yh.csx.crm.core.exception.BusinessException;
import com.yh.csx.crm.core.util.BeanUtils;
import com.yh.csx.crm.po.Customer;
import com.yh.csx.crm.service.AppTempService;
import com.yh.csx.crm.service.ApprovalService;
import com.yh.csx.crm.service.CustomerService;
import com.yh.csx.crm.service.request.*;
import com.yh.csx.crm.service.response.CompanyCodeInfoResp;
import com.yh.csx.crm.service.response.CustomerDetailsResp;
import com.yh.csx.crm.service.response.CustomerListResp;
import com.yh.csx.crm.service.vo.PageWrap;
import com.yh.csx.crm.service.vo.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * CustomerController class
 *
 * @author huyalin
 * @date 2019/2/13
 */
@Slf4j
@Api("客户管理服务")
@RestController
@RequestMapping("/customer")
public class CustomerController extends BaseController {

    @Autowired
    CustomerService customerService;

    @Autowired
    ApprovalService approvalService;

    @Autowired
    AppTempService appTempService;


    @ApiOperation("我的客户列表")
    @GetMapping("/list")
    public CommonResponse<PageWrap<List<CustomerListResp>>> getCustomerList(CustomerListReq req) {
        return super.visit(() -> {
            User user = new User(super.getUserId(), super.getUserName());
            return customerService.getCustomerList(user, req);
        });
    }

    @ApiOperation("获取客户信息")
    @GetMapping("/get")
    public CommonResponse<CustomerDetailsResp> getCustomer(Long customerId) {
        return super.visit(() -> {
            CustomerDetailsResp customerDetailsResp = customerService.getCustomerDetailsResp(customerId);
            return customerDetailsResp;
        });
    }

    @ApiOperation("客户转移")
    @PostMapping("/change")
    public CommonResponse changeCustomer(@RequestBody ChangeCustomerReq req) {
        return super.visit(() -> {
            User user = new User(super.getUserId(), super.getUserName());
            customerService.changeCustomer(user, req);

        });
    }

    @ApiOperation("禁用/启用")
    @PostMapping("/enable")
    public CommonResponse enable(Long customerId, Boolean enable) {
        return super.visit(() -> {
            User user = new User(super.getUserId(), super.getUserName());
            customerService.enable(user, customerId, enable);

        });
    }

    @ApiOperation("新增客户(保存草稿)")
    @PostMapping("/add")
    public CommonResponse addCustomer(@RequestBody @Validated CustomerAddReq req) {
        return super.visit(() -> {
            if (log.isDebugEnabled()) {
                log.debug("新增客户(保存草稿)" + req.toString());
            }
            User user = new User(super.getUserId(), super.getUserName());
            customerService.addCustomer(user, req);
        });
    }

    @ApiOperation("发起新建客户审批")
    @PostMapping("/start_approval")
    public CommonResponse startApproval(@RequestBody @Validated CustomerAddReq req) {
        return super.visit(() -> {
            if (log.isDebugEnabled()) {
                log.debug("发起新建客户审批" + req.toString());
            }
            User user = new User(super.getUserId(), super.getUserName());
            customerService.addCustomerAndStartApproval(user, req);
        });
    }

    @ApiOperation("发起临时信控额度审批")
    @PostMapping("/start_temp_credit_approval")
    public CommonResponse startTempCreditApproval(@RequestBody @Validated StartTempCreditApprovalReq req) {
        return super.visit(() -> {
            if (log.isDebugEnabled()) {
                log.debug("发起临时信控额度审批" + req.toString());
            }
            User user = new User(super.getUserId(), super.getUserName());
            appTempService.judgeTempLimit(req.getCustomerId(),req.getTempCredit(),req.getEndDate());
            customerService.startTempCreditApproval(user, req);
        });
    }

    @ApiOperation("发起固定信控额度审批")
    @PostMapping("/start_credit_approval")
    public CommonResponse startCreditApproval(@RequestBody StartCreditApprovalReq req) {
        return super.visit(() -> {
            if (log.isDebugEnabled()) {
                log.debug("发起固定信控额度审批" + req.toString());
            }
            User user = new User(super.getUserId(), super.getUserName());
            customerService.startCreditApproval(user, req);
        });
    }

    @ApiOperation("发起客户信息变更审批")
    @PostMapping("/start_modify_approval")
    public CommonResponse startModifyApproval(@RequestBody CustomerAddReq req) {
        return super.visit(() -> {
            if (log.isDebugEnabled()) {
                log.debug("发起客户信息变更审批" + req.toString());
            }
            User user = new User(super.getUserId(), super.getUserName());
            customerService.startCustomerModifyApproval(user, req);
        });
    }

    @ApiOperation("发起客户拓展公司")
    @PostMapping("/start_company_extl")
    public CommonResponse startCompanyExtl(@RequestBody CustomerCompanyExtlReq req) {
        return super.visit(() -> {
            if (log.isDebugEnabled()) {
                log.debug("发起客户拓展公司" + req.toString());
            }
            User user = new User(super.getUserId(), super.getUserName());
            Customer beforeCustomer = customerService.getCustomer(req.getId());
            Customer afterCustomer = BeanUtils.convert(Customer.class, beforeCustomer);
            if (Objects.isNull(beforeCustomer)) {
                throw new BusinessException("客户不存在");
            }
            if (!approvalService.isNotRepeatStart(req.getId())) {
                throw new BusinessException("已有审批中的单据");
            }
            afterCustomer.setCompanyCode(req.getCompanyCode());
            afterCustomer.setWrittenAmount(req.getWrittenAmount());
            afterCustomer.setPlanSalesAmount(req.getPlanSalesAmount());
            afterCustomer.setPaymentTerms(req.getPaymentTerms());
            afterCustomer.setPaymentDays(req.getPaymentDays());
            afterCustomer.setPayMode(req.getPayMode());
            afterCustomer.setCustomerLevel(req.getCustomerLevel());
            afterCustomer.setCreditLimit(req.getCreditLimit());
            if (null != req.getCooperationMode() && ("02").equals(req.getCooperationMode())){
                afterCustomer.setTempBeginTime(req.getTempBeginTime());
                afterCustomer.setTempEndTime(req.getTempEndTime());
            }
            //Customer beforeCustomer, Customer afterCustomer,
            approvalService.startApproval(user, ApprovalTypeEnum.EXT_COMPANY, beforeCustomer, afterCustomer, null);
        });
    }

    @ApiOperation("查询客户公司代码")
    @GetMapping("/company_code")
    public CommonResponse<List<String>> getCompanyCode(String customerName) {
        return super.visit(() -> {
            return customerService.getCustomerComp(customerName);
        });
    }

    @ApiOperation("扩公司根据公司代码变更页面信息")
    @GetMapping("/company_code/info")
    public CommonResponse<CompanyCodeInfoResp> getCompanyCodeInfo(Long customerId, String companyCode) {
        return super.visit(() -> {
            CompanyCodeInfoResp codeInfoResp = customerService.getCompanyCodeInfo(customerId, companyCode);
            return codeInfoResp;
        });
    }

    @ApiOperation("查询本客户要扩展的客户公司代码是否存在")
    @GetMapping("/company_code/if_not")
    public CommonResponse<Boolean> selectCustomerIfNot(Long customerId,String companyCode) {
        return super.visit(() -> {
            return customerService.selectCustomerIfNot(customerId, companyCode);
        });
    }
}